package com.ruoyi.web.controller.admin.api;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.admin.domain.ApiToken;
import com.ruoyi.admin.service.api.ApiTokenService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("/apiToken")
@RequiredArgsConstructor
public class ApiTokenController{

    private final ApiTokenService apiTokenService;

    /**
     * 生成 API Key
     */
    @PostMapping("/genApiKey")
    public AjaxResult genApiKey(@RequestBody @Validated ApiToken apiToken) {
        try {
            boolean success = apiTokenService.genApiKey(apiToken);
            if (success) {
                return AjaxResult.success(apiToken.getTokenType(), "生成成功");
            } else {
                return AjaxResult.error("生成失败");
            }
        } catch (Exception e) {
            log.error("生成 API Key 异常", e);
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 根据ApiKey查询整条记录
     */
    @GetMapping("/getApiTokenType")
    public AjaxResult getApiTokenType(@RequestHeader(value = "tokenType") String tokenType) {
        if (StringUtils.isEmpty(tokenType)) {
            return AjaxResult.error("缺少 tokenType");
        }
        try {
            ApiToken token = apiTokenService.getApiKey(tokenType);
            return token != null ? AjaxResult.success(token) : AjaxResult.error("无效 tokenType");
        } catch (Exception e) {
            log.error("查询 tokenType 失败", e);
            return AjaxResult.error("系统异常");
        }
    }
//
//    /**
//     * 根据apikey删除整行数据
//     * @param apiKey
//     * @return
//     */
//    @DeleteMapping("/deleteApiKey")
//    public AjaxResult deleteApiKey(@RequestHeader String apiKey) {
//        return apiTokenService.deleteApiKey(apiKey) ? AjaxResult.success() : AjaxResult.error();
//    }
//
//    /**
//     * 批量根据apikey删除整行数据
//     * @param apiKeys
//     * @return
//     */
//    @DeleteMapping("/deleteApiKeys")
//    public AjaxResult deleteApiKeys(@RequestParam("apiKey") List<String> apiKeys) {
//        return apiTokenService.deleteApiKeys(apiKeys) ;
//    }
}


